<?php
/**
 * Created by PhpStorm.
 * User: xiaomage
 * Date: 2020/12/8
 * Time: 17:26
 */

namespace common\data;

use think\Request;

abstract class DataSetter
{
    private $collect = [];

    /**
     * DataSetter constructor.
     * @param $params
     * @param array $collect
     */
    public function __construct($params, array $collect = [])
    {
        if ($params instanceof Request) {
            $params = $params->param();
        }

        $this->collect = $collect;

        $this->setter($params);
    }

    /**
     * @param $params
     * @return $this
     */
    public function setter($params)
    {
        $variable = new Variable();

        if ($this->collect) {
            $callback = function ($method, $param, $key) {
                if (method_exists($this, $method) && in_array($key, $this->collect)) {
                    call_user_func_array([$this, $method], [$param]);
                }
            };
        } else {
            $callback = function ($method, $param, $key = null) {
                if (method_exists($this, $method)) {
                    call_user_func_array([$this, $method], [$param]);
                }
            };
        }

        foreach ($params as $key => $item) {
            $method = 'set' . $variable->transToPascal($key);
            $callback($method, trim($item), $key);
        }

        return $this;
    }

    /**
     * @return array
     */
    public function toArray()
    {
        $variable = new Variable();
        $methods = get_class_methods($this);
        $data = [];
        if ($methods) {
            foreach ($methods as $item) {
                if (preg_match('/^get/', $item)) {
                    $name = preg_replace('/get/', '', $item);
                    if ($this->$item() !== null) {
                        $data[$variable->transToUnderline($name)] = $this->$item();
                    }
                }
            }
        }

        return $data;
    }
}